# -*- coding: utf-8
import markdown
import os
import sys
import getopt
from templates import html


def md2html(mdstr):
    exts = ['markdown.extensions.extra', 'markdown.extensions.codehilite',
            'markdown.extensions.tables', 'markdown.extensions.toc']

    ret = markdown.markdown(mdstr, extensions=exts)
    return html % ret

def write_html(md_path='blog.md', encoding='utf-8', html_path='../mysite/index.html'):

    with open(md_path, encoding=encoding)as infile, open(html_path, encoding=encoding, mode='w+')as outfile:
        md = infile.read()
        outfile.write(md2html(md))
    print('成功生成静态文件！')
    


if __name__ == '__main__':
    # 初始化参数
    inputfile = 'blog.md'
    outputfile = '../mysite/index.html'
    try:
        opts, args = getopt.getopt(sys.argv[1:], "hi:o:", ["ifile=", "ofile="])
    except getopt.GetoptError:
        print('md2html.py -i <inputfile> -o <outputfile>')
        sys.exit(2)

    # 无命令行参数的情况
    if not opts:
        write_html()
        sys.exit(0)

    for opt, arg in opts:
        if opt == '-h':
            print('md2html.py -i <inputfile> -o <outputfile>')
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-o", "--ofile"):
            outputfile = arg

    write_html(md_path=inputfile, html_path=outputfile)
